//
//  SelectionOfCell.m
//  PetAPP
//
//  Created by dllo on 16/1/24.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "SelectionOfCell.h"
#import "HeaderReusableView.h"
#import "NetworkingHandle.h"
#import "ModelOfContent.h"
#import "TwoPicsOfCell.h"
#import "ThirdPicsOfCell.h"
#import "SixPicsOfCell.h"
#import "OnePicsOfCell.h"
#import "FourPicsOfCell.h"
#import "NinePicsOfCell.h"
#import <MJRefresh.h>

@interface SelectionOfCell () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>;

@property (nonatomic, retain) UICollectionView *collection;

@property (nonatomic, retain) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, retain) NSMutableArray *dataArr;

@property (nonatomic, assign) NSInteger refreshNum;

@property (nonatomic, retain) UIButton *buttonOfTop;

@end

@implementation SelectionOfCell

- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        [self createCollectionViewWithFrame:(CGRect){.size = frame.size}];
        
        [self handleData];
        [self handleRefresh];
    }
    return self;
}

- (void)handleRefresh {
    
    self.collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.refreshNum = 1;
        [self handleData];
    }];
    
    self.collection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.refreshNum++;
        [self handleData];
    }];
}

/** 加载数据 */
- (void)handleData {
    NSString *url = @"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=threadListNew";
    NSString *body = [NSString stringWithFormat:@"condition=digest&page=1&pagesize=%ld0&version=d1bd83a33f1a841ab7fda32449746cc4", self.refreshNum];
    NSDictionary *dic = @{@"Content-Type" : @"application/x-www-form-urlencoded"};
    
    [NetworkingHandle handleWorkData:url AndBody:body value:dic handleBlock:^(id result) {
        self.dataArr = [NSMutableArray new];
        NSArray *tempArr = [result objectForKey:@"array"];
        
        for (NSDictionary *dic in tempArr) {
            ModelOfContent *model = [[ModelOfContent alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArr addObject:model];
            [model release];
        }
        [self.collection reloadData];
        
        [self.collection.mj_header endRefreshing];
        [self.collection.mj_footer endRefreshing];
    }];
    

}
/** 创建CollectionView */
- (void)createCollectionViewWithFrame:(CGRect)frame {
    self.refreshNum = 1;
    
    CGFloat width = self.frame.size.width;
    self.flowLayout = [UICollectionViewFlowLayout new];
    self.flowLayout.itemSize = CGSizeMake(width, 300);
    
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.flowLayout.minimumLineSpacing = 10;
    self.flowLayout.headerReferenceSize = CGSizeMake(width, 250);
    
    
    self.collection = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:self.flowLayout];
    self.collection.backgroundColor = [UIColor colorWithRed:0.9625 green:0.9625 blue:0.9625 alpha:1.0];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    [self addSubview:self.collection];
    [_collection release];
    self.collection.showsVerticalScrollIndicator = NO;
    
    self.collection.scrollsToTop = YES;
    
    
    [self.collection registerClass:[OnePicsOfCell class] forCellWithReuseIdentifier:@"poolOfOne"];
    [self.collection registerClass:[TwoPicsOfCell class] forCellWithReuseIdentifier:@"poolOfTwo"];
    [self.collection registerClass:[ThirdPicsOfCell class] forCellWithReuseIdentifier:@"poolOfThird"];
    [self.collection registerClass:[FourPicsOfCell class] forCellWithReuseIdentifier:@"poolOfFour"];
    [self.collection registerClass:[SixPicsOfCell class] forCellWithReuseIdentifier:@"poolOfSix"];
    [self.collection registerClass:[NinePicsOfCell class] forCellWithReuseIdentifier:@"poolOfNine"];
    
    [self.collection registerClass:[HeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"poolOfHeader"];
    
    
    
    
    self.buttonOfTop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonOfTop.frame = CGRectMake(self.frame.size.width - 55, self.frame.size.height - 50, 40, 40);
    [self addSubview:self.buttonOfTop];
    [self.buttonOfTop setImage:[UIImage imageNamed:@"top"] forState:UIControlStateNormal];
    
    UIBezierPath *backgroundPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 3, 40, 40) cornerRadius:20];
    
    self.buttonOfTop.layer.shadowPath = backgroundPath.CGPath;
    self.buttonOfTop.layer.shadowOpacity = 0.9;
    self.buttonOfTop.layer.shadowRadius = 0;
    self.buttonOfTop.layer.shadowColor = [UIColor colorWithRed:1.0 green:0.8964 blue:0.2489 alpha:1.0].CGColor;
    [self.buttonOfTop addTarget:self action:@selector(backTopWithButton:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)backTopWithButton:(UIButton *)button {
    // 当点击 button 回到顶部
    [self.collection scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    

}


/** 设置cell行数 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.dataArr.count;
}
#pragma mark - 设置cell的样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ModelOfContent *model = self.dataArr[indexPath.item];
    
    if (model.pics.count == 1){
        OnePicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfOne" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        [cell passContentWithModel:model];
        
        return cell;
    }else if (model.pics.count == 2) {
        TwoPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfTwo" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    } else if (model.pics.count == 3) {
        ThirdPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfThird" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    } else if (model.pics.count >= 4 && model.pics.count <= 5){
        FourPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfFour" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        [cell passContentWithModel:model];
        
        return cell;
        
        
    }else if (model.pics.count >= 6 && model.pics.count <= 8) {
        SixPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfSix" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    } else {
        NinePicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfNine" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    }
    
    
    
}
#pragma mark - 返回头部的样式
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    HeaderReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"poolOfHeader" forIndexPath:indexPath];
    
    return header;
}

#pragma mark - 返回每一行高度的方法
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelOfContent *model = [self.dataArr objectAtIndex:indexPath.item];
    
    
    return CGSizeMake(self.frame.size.width, [CellOfContent returnCGSizeForModel:model]);

}

#pragma mark - 实现代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    ModelOfContent *model = [self.dataArr objectAtIndex:indexPath.item];
    
    if ([model.newmark isEqualToString:@"1"]) {
        NSString *tid = [NSString stringWithFormat:@"tid=%@&version=d1bd83a33f1a841ab7fda32449746cc4",model.tid];
        NSDictionary *dic = @{@"url" : @"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=threadDetailNew",
                              @"body": tid,
                              @"value": @{@"Content-Type" : @"application/x-www-form-urlencoded"}};
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PushVC" object:@"1" userInfo:@{@"dic1":dic}];
    }else {
        
        
        NSString *tid = [NSString stringWithFormat:@"id=leepet_thread%%3Aapi&isapple=1&tid=%@&uid=1411934&version=d1bd83a33f1a841ab7fda32449746cc4",model.tid];
        NSDictionary *dic = @{@"url" : @"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=threadshowfirst",
                              @"body": tid,
                              @"value": @{@"Content-Type" : @"application/x-www-form-urlencoded"}};
        NSString *tid2 = [NSString stringWithFormat:@"isdesc=1&onlyauthor=0&page=1&pagesize=10&tid=%@&uid=1411934&version=d1bd83a33f1a841ab7fda32449746cc4",model.tid];
        NSDictionary *dic2 = @{@"url" : @"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=threadshowlayer",
                               @"body": tid2,
                               @"value": @{@"Content-Type" : @"application/x-www-form-urlencoded"}};
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PushVC" object:@"0" userInfo:@{@"dic1": dic, @"dic2": dic2}];
    }
    
    


}




/** collectionCell 的子控件的布局通常在此方法中设置 */
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    
//    NSLog(@"%@",layoutAttributes);
    self.contentView.backgroundColor = [UIColor colorWithRed:0.9625 green:0.9625 blue:0.9625 alpha:1.0];
    
}

- (void)dealloc {
    [_buttonOfTop release];
    [_dataArr release];
    [_collection release];
    [_flowLayout release];
    [super dealloc];
}

@end
